const Koa = require('koa');
const Router = require('@koa/router');
const views = require('koa-views');
const fs = require('fs')

const app = new Koa();
const router = new Router();

// 页面
router.get('/', async (ctx, next) => {
  await ctx.render('index.html')
});

// json 数据

// 获取列表
router.get('/api/getGoodsList', async ctx => {
  // 参数
  // 逻辑
  const res = JSON.parse(fs.readFileSync('./goods.json', 'utf8'));
  // 返回
  ctx.body = res;
})

// 添加
router.get('/api/goodsNumAdd', async ctx => {
  // 参数
  const { id } = ctx.query;
  // 逻辑
  const res = JSON.parse(fs.readFileSync('./goods.json', 'utf8'));
  const index = res.list.findIndex(item => item.id == id)
  res.list[index].num++
  fs.writeFileSync('./goods.json', JSON.stringify(res))
  // 返回
  ctx.body = res;
})


// 减少
router.get('/api/goodsNumLess', async ctx => {
  // 参数
  const { id } = ctx.query;
  // 逻辑
  const res = JSON.parse(fs.readFileSync('./goods.json', 'utf8'));
  const index = res.list.findIndex(item => item.id == id)
  res.list[index].num--
  fs.writeFileSync('./goods.json', JSON.stringify(res))
  // 返回
  ctx.body = res;
})

app
  .use(views(__dirname + '/views'))
  .use(router.routes())
  .listen(7001, () => {
    console.log('http://localhost:7001');
  });